<template>
	<div class='app-container'>
		<el-form class="filter-container" label-position="left" label-width="68px">
			<el-row :gutter="24">
				<el-col :span="4">
					<el-form-item label="事件名称" style="margin-bottom: 0!important;">
						<el-input @keyup.enter.native="getList" class="filter-item" placeholder="请输入名称" v-model.trim="listQuery.eventName"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="事件类型" style="margin-bottom: 0!important;">
						<el-select v-model="listQuery.eventType" clearable placeholder="请选择">
							<el-option v-for="item in myEvtTypes" :key="item.eventType" :label="item.typeCd" :value="item.eventType"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="事件时间" style="margin-bottom: 0!important;">
						<el-date-picker type="datetimerange" :default-time="['00:00:00', '23:59:59']" @keyup.enter.native="getList" class="filter-item" align="right" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" v-model="time" :picker-options="pickerOptions">
						</el-date-picker>
					</el-form-item>
				</el-col>
				<el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList">{{$t('table.search')}}</el-button>
				<el-button :loading="refreshing" class="filter-item el-icon-refresh" style="margin-left: 10px;" @click="refreshList" type="danger">&nbsp;刷新列表</el-button>
				<el-button class="filter-item" @click="handleShow(true)" type="success" icon="el-icon-plus">新增</el-button>
			</el-row>
		</el-form>
		<el-table stripe :data="tableData" v-loading="listLoading" element-loading-text="加载中..." border fit highlight-current-row style="width: 100%">
			<el-table-column prop="eventName" label="事件名称" align="center"></el-table-column>
			<el-table-column prop="typeCd" label="事件类型" align="center"></el-table-column>
			<el-table-column prop="eventNation" label="国家" align="center"></el-table-column>
			<el-table-column align="center" label="事件状态" width="80">
				<template slot-scope="scope">
					<el-tag size="small" :type="checkClass(scope.row.dataStatus)">{{checkStatu(scope.row.dataStatus)}}</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="eventStart" label="事件开始时间" align="center"></el-table-column>
			<el-table-column prop="eventEnd" label="事件结束时间" align="center"></el-table-column>
			<el-table-column prop="createTime" label="事件创建时间" align="center"></el-table-column>
			<el-table-column prop="updater" label="创建人" align="center"></el-table-column>
			<el-table-column align="center" :label="$t('table.actions')" width="150" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button size="mini" @click="handleShow(false, scope.row)" :disabled='scope.row.eventType == 5'>编辑</el-button>
					<el-button size="mini" type="danger" @click="handleDelete(scope.row)" :disabled='scope.row.eventType == 5'>删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div class="pagination-container">
			<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNum" :page-sizes="[10,20,30, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
		</div>

		<el-dialog :close-on-click-modal="false" :title="dialogStatus ? '新增事件': '编辑事件'" width="80%" :visible.sync="dialogFormVisible">
			<el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="130px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="事件名称" prop="eventName">
							<el-input v-model.trim="temp.eventName" type="text" placeholder="请输入" :maxlength='50'></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="事件起始时间" prop="evtTime">
						    <el-date-picker
						      	v-model="temp.evtTime"
						      	type="datetimerange"
								range-separator="至"
						      	start-placeholder="开始时间"
						      	end-placeholder="结束时间">
						    </el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="事件类型" prop="eventType">
							<el-select v-model="temp.eventType" clearable placeholder="请选择">
								<el-option v-for="item in evtTypes" :key="item.eventType" :label="item.typeCd" :value="item.eventType"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="相关国家" prop="eventNation">
							<el-select v-model="temp.eventNation" filterable clearable placeholder="请选择">
								<el-option v-for="(item, index) in nations" :key="index" :label="item" :value="item"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="temp.eventType == 6">
						<el-form-item label="前值" prop="prevalue">
							<el-input v-model.trim="temp.prevalue" placeholder="请输入" :maxlength='20'></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="temp.eventType == 6">
						<el-form-item label="今值" prop="currentvalue">
							<el-input v-model.trim="temp.currentvalue" placeholder="请输入" :maxlength='20'></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="相关板块" prop="plates">
							<el-select 
								v-model="temp.plates" 
								clearable 
								multiple 
								remote 
								reserve-keyword 
								:remote-method="filterPlate" 
								filterable 
								value-key='code'
								placeholder="请输入选择">
								<el-option-group v-if="filterPlateList.filter(e => e.type === 0).length" key="概念板块" label="概念板块">
									<el-option v-for="(item, index) in filterPlateList.filter(e => e.type === 0)" :key="item.code" :label="item.name+'('+item.code+')'" :value="item"></el-option>
								</el-option-group>
								<el-option-group v-if="filterPlateList.filter(e => e.type === 1).length" key="行业板块" label="行业板块">
									<el-option v-for="(item, index) in filterPlateList.filter(e => e.type === 1)" :key="item.code" :label="item.name+'('+item.code+')'" :value="item"></el-option>
								</el-option-group>
								<el-option-group v-if="filterPlateList.filter(e => e.type === 2).length" key="原创板块" label="原创板块">
									<el-option v-for="(item, index) in filterPlateList.filter(e => e.type === 2)" :key="item.code" :label="item.name+'('+item.code+')'" :value="item"></el-option>
								</el-option-group>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button v-if="!dialogStatus" type="success" @click="updateAuditData">审核通过</el-button>
				<el-button type="primary" @click="updateData">保存</el-button>
				<el-button @click="dialogFormVisible = false">关闭</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import { selectInfo, selectData, addInfo, updateInfo, toolDelete, addInfoSc, updateSc } from '@/api/toolManage'
	import { articleAllPlateList } from '@/api/article'
	import pinyin from 'pinyin'

	export default {
		name: 'calendar',
		created() {
			this.getList()
			this.getEventType()
			this.getPlateList()  //获取相关板块数据
			this.userName = this.$store.state.user.name
		},
		methods: {
			getList() {
				this.listLoading = true
				if(this.time){
					this.listQuery.eventStart = this.time[0]
					this.listQuery.eventEnd = this.time[1]
				}else{
					this.listQuery.eventStart = ''
					this.listQuery.eventEnd = ''
				}
				selectInfo(this.listQuery).then(res => {
					this.tableData = res.Data
					this.total = res.total * 1
					this.listLoading = false
				})
			},
			getEventType() {
				selectData().then(res => {
					this.evtTypes = res.Data
				})
			},
			handleSizeChange(val) {
				this.listQuery.pageSize = val
				this.getList()
			},
			handleCurrentChange(val) {
				this.listQuery.pageNum = val
				this.getList()
			},
			handleShow(boo, row) {
				this.dialogStatus = boo
				this.filterPlateList = []
				if(boo) {
					this.temp = {
						eventName: '',
						eventType: '',
						prevalue: '',
						currentvalue: '',
						eventNation: '',
						eventStart: '',
						eventEnd: '',
						evtTime: '',
						plates: []
					}
				} else {
					this.innitPlate(row.plates);
					const obj = {
						'id': row.id,
						'eventName': row.eventName,
						'eventType': row.eventType,
						'prevalue': row.prevalue,
						'currentvalue': row.currentvalue,
						'eventNation': row.eventNation,
						'evtTime': [row.eventStart, row.eventEnd],
						'updater': row.updater,
						'plates': row.plates
						// 'plates': row.plates.map(val => { return val.name+'('+val.code+')'})
					}
					this.temp = Object.assign({}, obj)
				}
				this.dialogFormVisible = true
				this.$nextTick(() => {
					this.$refs['dataForm'].clearValidate()
				})
			},
			updateAuditData() {
				this.$refs['dataForm'].validate(valid => {
					if(valid) {
						let obj = Object.assign({}, this.temp)
						obj.eventStart = this.temp.evtTime[0]
						obj.eventEnd = this.temp.evtTime[1]
						obj.dataStatus = 1
						obj.updater = this.userName
						delete obj.evtTime
						if(obj.eventType !== 6){
							obj.currentvalue = ''
							obj.prevalue = ''
						} else {
							obj.prevalue = this.turnNum(obj.prevalue);
							obj.currentvalue = this.turnNum(obj.currentvalue);
						}
						updateInfo(obj).then(() => {
							this.getList()
							this.dialogFormVisible = false
							this.$notify({ title: '成功', message: '审核成功', type: 'success', duration: 2000 })
						}).catch(errCode => {
							if(errCode == 201){
								this.$confirm('该事件已存在, 是否继续?', '提示', {
									confirmButtonText: '确定',
									cancelButtonText: '取消',
									type: 'warning'
								}).then(() => {
								 	updateSc(obj).then(() => {
										this.getList()
										this.dialogFormVisible = false
										this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
								 	})
								}).catch(() => {
									this.$message({ type: 'info', message: '已取消' })
								})
							}
						})
					} else {
			            console.log('error submit!!');
			            return false;
		          	}
				})
			},
			turnNum(val){
				if(isNaN(val)){ //填了是百分数
					let item = parseFloat(val);
		    		return Math.round(item*10000)/10000 + '%';
			   	} else if(val) { //填了并且不是百分数
			    	return Math.round(val*10000)/10000;
			    } else {  //没填
			    	return val
			    }
			},
			updateData() {
				this.$refs['dataForm'].validate(valid => {
					if(valid) {
						let obj = Object.assign({}, this.temp)
						obj.eventStart = this.temp.evtTime[0]
						obj.eventEnd = this.temp.evtTime[1]
						obj.dataStatus = 0
						obj.updater = this.userName
						delete obj.evtTime
						if(obj.eventType !== 6){
							obj.currentvalue = ''
							obj.prevalue = ''
						} else {
							obj.prevalue = this.turnNum(obj.prevalue);
							obj.currentvalue = this.turnNum(obj.currentvalue);
						}
						if(this.dialogStatus){
							addInfo(obj).then(() => {
								this.getList()
								this.dialogFormVisible = false
								this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
							}).catch(errCode => {
								if(errCode == 201){
									this.$confirm('该事件已存在, 是否继续?', '提示', {
										confirmButtonText: '确定',
										cancelButtonText: '取消',
										type: 'warning'
									}).then(() => {
									 	addInfoSc(obj).then(() => {
											this.getList()
											this.dialogFormVisible = false
											this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
									 	})
									}).catch(() => {
										this.$message({ type: 'info', message: '已取消' })
									})
								}
							})
						} else {
							updateInfo(obj).then(() => {
								this.getList()
								this.dialogFormVisible = false
								this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
							}).catch(errCode => {
								if(errCode == 201){
									this.$confirm('该事件已存在, 是否继续?', '提示', {
										confirmButtonText: '确定',
										cancelButtonText: '取消',
										type: 'warning'
									}).then(() => {
									 	updateSc(obj).then(() => {
											this.getList()
											this.dialogFormVisible = false
											this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
									 	})
									}).catch(() => {
										this.$message({ type: 'info', message: '已取消' })
									})
								}
							})
						}
					} else {
			            console.log('error submit!!');
			            return false;
		          	}
				})
			},
			handleDelete(tar) {
				this.$confirm('确认删除, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					let obj = {
					    id: tar.id,
					    updater: this.userName
					}
					toolDelete(obj).then(() => {
						this.getList()
						this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
					})
				}).catch(() => {
					this.$message({ type: 'info', message: '已取消删除' })
				})
			},
			refreshList() {
				this.refreshing = true
				const params = Object.assign({}, this.listQuery)
				if(this.listQuery.updateTime) {
					params.startUpdateTime = this.listQuery.updateTime[0]
					params.endUpdateTime = this.listQuery.updateTime[1]
				} else {
					params.startUpdateTime = ''
					params.endUpdateTime = ''
				}
				selectInfo(params).then(res => {
					this.refreshing = false
					this.tableData = res.Data
					this.total = parseInt(res.total)
					this.$message({ message: '刷新成功', type: 'success' })
				}).catch(() => {
					this.refreshing = false
				})
			},
			checkClass(data) {
				switch(data) {
					case 0:
						return 'warning' // '未审核'
					case 1:
						return 'success' // '已审核'
				}
			},
			checkStatu(data) {
				switch(data) {
					case 0:
						return '未审核'
					case 1:
						return '已审核'
				}
			},
	      	getPlateList () {
		        articleAllPlateList({ pageNum: 1, pageSize: 99999 }).then(res => {
		          	this.allPlateList = res.Data
		        })
	      	},
			filterMethod(str){
				let result = this.allPlateList.filter(item => {
					return item.name.indexOf(str) > -1 || item.code.indexOf(str) > -1 || pinyin(item.name, {
						style: pinyin.STYLE_FIRST_LETTER,
						heteronym: true
					}).join('').indexOf(str) > -1
				}).sort((a, b) => a.name.length - b.name.length)
				return result
			},
			innitPlate(arr){
				if(arr.length){
					arr.forEach(item =>{
						const query = item.name
						let arr = this.filterMethod(query)
						this.filterPlateList = this.filterPlateList.concat(arr)
					})
				}
			},
			filterPlate(query) {
				if(query !== '') {
					let result = this.allPlateList.filter(item => {
						return item.name.indexOf(query) > -1 || item.code.indexOf(query) > -1 || pinyin(item.name, {
							style: pinyin.STYLE_FIRST_LETTER,
							heteronym: true
						}).join('').indexOf(query) > -1
					}).sort((a, b) => a.name.length - b.name.length)
					if(result.length >= 100) {
						this.$message({ message: '菜单超过100条，只显示前100条，请输入更多信息' })
						result = result.slice(0, 99)
					}
					this.filterPlateList = result
				} else {
					this.filterPlateList = []
				}
			},
		},
		data() {
			let timeSelect = (rule, value, callback) => {
				if(value) {
					callback()
				} else {
					callback(new Error('请选择事件起始时间'))
				}
			}
//	      	let checkNum = (rule, value, callback) => {
//		    	if(value == ""){
//		    		callback()
//		    		return
//			    }
//		    	if(isNaN(value)){
//		    		callback(new Error('请输入数字值'))
//			    } else {
//			    	callback()
//			    }
//	      	};
	      	let checkNum = (rule, value, callback) => {
		    	if(value == ""){
		    		callback()
		    		return
			    };
		    	let reg = /^[-0-9.%]+$/;
		    	if(reg.test(value)){
		    		callback()
			    } else {
			    	callback(new Error('请输入数字值或百分数'))
			    }
	      	};
			return {
				evtTypes: [],
				nations: ['中国','中国香港','中国台湾','中国澳门','美国','欧盟','日本','韩国','越南','泰国','意大利','瑞士','新西兰','新加坡','澳大利亚','加拿大','法国','德国','英国','瑞士','印度','阿根廷','巴西','俄罗斯','土耳其','菲律宾'],
				refreshing: false,
		        allPlateList: [],
        		filterPlateList: [],
				total: null,
				myEvtTypes: [
					{ typeCd: "会议", eventType: 1 },
					{ typeCd: "数据", eventType: 2 },
					{ typeCd: "大事", eventType: 3 },
					{ typeCd: "节日", eventType: 4 },
					{ typeCd: "IPO", eventType: 5 },
					{ typeCd: "经济", eventType: 6 }
				],
				listLoading: false,
				time: ['', ''],
				listQuery: {
					pageNum: 1,
					pageSize: 20,
					eventType: '',
					eventName: '',
					eventStart: '',
					eventEnd: ''
				},
				userName:'',
				dialogStatus: '',
				dialogFormVisible: false,
				tableData: [],
				temp: {},
				rules: {
		          	eventName: [{ required: true, message: '请填写事件名称', trigger: 'blur' }],
      	          	eventType: [{ required: true, message: '请选择事件类型', trigger: 'change' }],
      	          	currentvalue: [{ validator: checkNum, trigger: 'blur' }],
      	          	prevalue: [{ validator: checkNum, trigger: 'blur' }],
      	          	// eventNation: [{ required: true, message: '请选择相关国家', trigger: 'change' }],
	          	 	evtTime: [{ required: true, validator: timeSelect, trigger: 'change' }]
      	          	// plates: [{ required: true, message: '请选择相关板块', trigger: 'change' }],
				},
				pickerOptions: {
					shortcuts: [{
						text: '今天',
						onClick(picker) {
							const end = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1).getTime() - 1000
							const start = end + 1000 - 3600 * 1000 * 24
							picker.$emit('pick', [start, end])
						}
					}, {
						text: '最近三天',
						onClick(picker) {
							const end = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1).getTime() - 1000
							const start = end + 1000 - 3600 * 1000 * 24 * 3
							picker.$emit('pick', [start, end])
						}
					}, {
						text: '最近一周',
						onClick(picker) {
							const end = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1).getTime() - 1000
							const start = end + 1000 - 3600 * 1000 * 24 * 7
							picker.$emit('pick', [start, end])
						}
					}]
				}
			}
		}
	}
</script>

<style type="scss" scoped>
	.col { margin: auto; } .card-body { margin-top: 1rem; } .form { max-width: 500px !important; margin: auto !important; }
</style>

<style scoped>
	.el-tag {
		margin-right: 3px;
		background-color: rgba(64, 158, 255, .1);
		color: #409EFF;
		border-radius: 4px;
		padding: 0 3px;
		-webkit-box-sizing: border-box;
		box-sizing: border-box;
		border: 1px solid rgba(64, 158, 255, .2);
	}
</style>